package com.fancyy.scm.activity;

import android.app.Activity;
import android.content.Intent;
import android.databinding.ObservableField;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;

import com.fancyy.scm.R;
import com.fancyy.scm.base.BaseActivity;
import com.fancyy.scm.base.adapter.BRBaseAdapter;
import com.fancyy.scm.base.annotation.Layout;
import com.fancyy.scm.base.annotation.Translucent;
import com.fancyy.scm.base.http.BRDataListener;
import com.fancyy.scm.base.http.BRDataTransport;
import com.fancyy.scm.bean.CartonInfoItem;
import com.fancyy.scm.databinding.ActivityPrintTrayCodeBinding;
import com.fancyy.scm.util.ImgUtil;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;
import java.util.List;

import zpSDK.zpSDK.zpBluetoothPrinter;

import static com.fancyy.scm.BRConstant.GET_PRINTIMG_BY_TRAYBARCODE;
import static com.fancyy.scm.BRConstant.GET_TRAY_INFO_BY_CARTONBARCODE;

@Translucent
@Layout(R.layout.activity_print_tray_code)
public class PrintTrayCodeActivity extends BaseActivity<ActivityPrintTrayCodeBinding> {

    /**
     * 创建接口对象
     */
    private zpBluetoothPrinter mZpAPI;

    /**
     * 获取当前activity对象
     *
     * @return 返回当前activity对象
     */
    private Activity getActivity() {
        return this;
    }

    public ObservableField<String> TrayCode = new ObservableField<>();
    BRBaseAdapter adapter = new BRBaseAdapter();
    List<Object> list = new ArrayList<>();

    public  void onConnectPrinterClick(View view){
        Intent intent = new Intent(this, ConnectPrinterActivity.class);
        intent.putExtra("type", 3);
        startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        init();
        setNeedScan(true);
        super.onCreate(savedInstanceState);
        adapter.init(this, R.layout.cartonlistitem, list);
        getDataBinding().listView.setAdapter(adapter);
    }
    public void onScanClick(View view) {
        if(!getPDA()) {
            Intent intent = new Intent(this, CaptureActivity.class);
            startActivityForResult(intent, 1);
        }
    }
    @Override
    public void doScan(String data) {
        SearchCartonListByCartonCode(data);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1 && resultCode == RESULT_OK) {
            String code = data.getStringExtra(CodeUtils.RESULT_STRING);
            getDataBinding().scan.setText(code);
            SearchCartonListByCartonCode(code);
        }
    }

    public  void  onPrintsClick(View view)
    {
        BRDataTransport.createGet(GET_PRINTIMG_BY_TRAYBARCODE + "?barcode=" +  getDataBinding().TrayBarCode.getText().toString())
                .addProgressing(this, "Progressing...")
                .execute(new BRDataListener() {
                    @Override
                    public void onSuccess(Object data) {
                        String picData = ((LinkedTreeMap) data).get("pic").toString();
                        try {
                            boolean isprintsucess = mZpAPI.drawBitmap(ImgUtil.stringToBitmap(picData), 0, 0, 600, 650, 0, 1);
                            if (isprintsucess)
                                showToast("Print success");
                            else
                                showToast("Print failed");

                        } catch (Exception ex) {
                            showToast("Print failed, please connect to printer");
                        }
                    }
                });

    }

    public  void SearchCartonListByCartonCode(String code)
    {
        getDataBinding().scan.setText(code);
        BRDataTransport.createGet(GET_TRAY_INFO_BY_CARTONBARCODE+"?barcode="+getDataBinding().scan.getText().toString())
                .addProgressing(this, "Progressing...")
                .execute(new BRDataListener<List< CartonInfoItem>>() {
                    @Override
                    public void onSuccess(List<CartonInfoItem> data) {
                        list.clear();
                        if (data != null && data.size() > 0) {
                            list.addAll(data);
                            getDataBinding().TrayBarCode.setText(data.get(0).trayBarCode);
                        } else {
                            showToast("No data be found");
                        }
                        adapter.notifyDataSetChanged();
                    }
                    @Override
                    public void onFail(int status, String failMessage) {
                        showToast("The code has bean scanned or do not exist");
                    }
                }, new TypeToken<List<CartonInfoItem>>(){});
    }

    /**
     * 初始化打印控件
     */
    private void init() {
        //打印控件不为null,进行实例化
        if (mZpAPI == null) {
            mZpAPI = new zpBluetoothPrinter(getActivity());
        }
    }

    /**
     * 打印标签
     *
     * @return 打印是否成功
     */
    private boolean printLabel(String trayBarCode) {
        //获取图片
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.car);
        /*
         *打印标签方法
         * 1.bitmap 需要打印的图像
         * 2.xx 标签x轴偏移（单位像素）
         * 3.yy 标签y轴偏移（单位像素）
         * 4.width 标签宽度（单位像素）
         * 5.height 标签高度（单位像素）
         * 6.Rotate 旋转角度（0,90,180,270）
         * 7.gotopaper 标签类型定位类型 0连续纸,1间隙纸,2 左侧黑标定位,3右侧黑标定位,4孔定位,5背部黑标定位
         */
        return mZpAPI.drawBitmap(bitmap, 0, 0, 400, 240, 0, 1);

    }

}